/**
 * 班级服务模块
 */

const { addClass, updateClass, getClassList, exists } = require('../db/class_list');
const { getTeacherStatus } = require('../db/teachers');

/**
 * 添加班级
 * @param {*} ctx 
 */
const add = async ctx => {
    try {
        const obj = ctx.request.body;
        const n = await exists(obj.name, 0);
        if (n) {
            return ctx.body = {
                code: 0,
                msg: '已存在相同的班级名称'
            }
        }
        const teacher = await getTeacherStatus(obj.teacher_id);
        if (!teacher) {
            return ctx.body = {
                code: 0,
                msg: '教师不存在'
            }
        }
        if (!teacher.status) {
            return ctx.body = {
                code: 0,
                msg: '此教师已离职'
            }
        }
        await addClass(obj);
        ctx.body = {
            code: 1,
            msg: '班级添加成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '班级添加失败，请稍后再试'
        }
    }
}

/**
 * 添加班级
 * @param {*} ctx 
 */
const update = async ctx => {
    try {
        const obj = ctx.request.body;
        const { id } = obj;
        delete obj.id;
        const n = await exists(obj.name, id);
        if (n) {
            return ctx.body = {
                code: 0,
                msg: '已存在相同的班级名称'
            }
        }
        const teacher = await getTeacherStatus(obj.teacher_id);
        if (!teacher) {
            return ctx.body = {
                code: 0,
                msg: '教师不存在'
            }
        }
        if (!teacher.status) {
            return ctx.body = {
                code: 0,
                msg: '此教师已离职'
            }
        }
        await updateClass(id, obj);
        ctx.body = {
            code: 1,
            msg: '班级修改成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '班级修改失败，请稍后再试'
        }
    }
}

/**
 * 添加班级
 * @param {*} ctx 
 */
const getList = async ctx => {
    try {
        const [data, total] = await getClassList(ctx.request.query);
        ctx.body = {
            code: 1,
            data,
            total
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '班级获取失败，请稍后再试'
        }
    }
}

module.exports = {
    add,
    update,
    getList
}